from Crypto.Cipher import AES
from Crypto import Random
import os

BS = 16
pad = lambda s: s + (BS - len(s.encode('utf8')) % BS) * chr(BS - len(s.encode('utf8')) % BS) 
unpad = lambda s : s[0:-s[-1]]

class Crypt():

    def encrypt2( self, raw, key ):
        secret = os.urandom(16)
        crypto = AES.new(key, AES.MODE_CTR, counter=lambda: secret)
        return secret + crypto.encrypt(raw)

    def decrypt2( self, enc, key ):
        secret = enc[:16]
        crypto = AES.new(key, AES.MODE_CTR, counter=lambda: secret )
        return crypto.decrypt( enc[16:] )

    def encrypt( self, raw, key ):
        raw = pad(raw)
        iv = Random.new().read( AES.block_size )
        cipher = AES.new( key, AES.MODE_CBC, iv )
        return iv + cipher.encrypt( raw )

    def decrypt( self, enc, key ):
        iv = enc[:16]
        cipher = AES.new(key, AES.MODE_CBC, iv )
        dec = cipher.decrypt( enc[16:] )
        return unpad(dec)